/*
 * KindleCollView.java
 */
package com.vs.kindlecoll.UI;

import com.vs.kindlecoll.Beans.Book;
import com.vs.kindlecoll.IO.BookHashIniter;
import com.vs.kindlecoll.IO.KindleInteractor;

import java.awt.Color;
import java.awt.Component;
import java.awt.dnd.DragSource;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.application.Action;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.Task;

import javax.swing.DefaultListCellRenderer;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JList;

/**
 * The application's main frame.
 */
public class KindleCollView extends FrameView {

    public KindleCollView(SingleFrameApplication app) {
        super(app);

        initComponents();
        try {
            extraInit();
        } catch (Exception ex) {
            Logger.getLogger(KindleCollView.class.getName()).log(Level.SEVERE, null, ex);
        }
        TreeModelInit();

    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = KindleCollApp.getApplication().getMainFrame();
            aboutBox = new KindleCollAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        KindleCollApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jListBooks = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTreeCollections = new javax.swing.JTree();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();

        mainPanel.setName("mainPanel"); // NOI18N

        jSplitPane1.setName("jSplitPane1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jListBooks.setModel(new javax.swing.AbstractListModel() {
            Book[] books = { new Book("Item 1"), new Book("Item 2"), new Book("Item 2")};
            public int getSize() { return books.length; }
            public Object getElementAt(int i) { return books[i]; }
        });
        jListBooks.setDragEnabled(true);
        jListBooks.setName("jListBooks"); // NOI18N
        jListBooks.setCellRenderer(new BooksListCellRenderer());
        jScrollPane1.setViewportView(jListBooks);

        jSplitPane1.setLeftComponent(jScrollPane1);

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jTreeCollections.setModel(null);
        jTreeCollections.setDragEnabled(true);
        jTreeCollections.setDropMode(javax.swing.DropMode.INSERT);
        jTreeCollections.setEditable(true);
        jTreeCollections.setName("jTreeCollections"); // NOI18N
        jScrollPane2.setViewportView(jTreeCollections);

        jSplitPane1.setRightComponent(jScrollPane2);

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 726, Short.MAX_VALUE)
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 337, Short.MAX_VALUE)
                .addContainerGap())
        );

        menuBar.setName("menuBar"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(com.vs.kindlecoll.UI.KindleCollApp.class).getContext().getResourceMap(KindleCollView.class);
        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(com.vs.kindlecoll.UI.KindleCollApp.class).getContext().getActionMap(KindleCollView.class, this);
        jMenuItem1.setAction(actionMap.get("DoGenerationTask")); // NOI18N
        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
        jMenuItem1.setActionCommand(resourceMap.getString("jMenuItem1.actionCommand")); // NOI18N
        jMenuItem1.setName("jMenuItem1"); // NOI18N
        fileMenu.add(jMenuItem1);

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        jMenu1.setText(resourceMap.getString("jMenu1.text")); // NOI18N
        jMenu1.setName("jMenu1"); // NOI18N

        jMenuItem2.setAction(actionMap.get("DelElement")); // NOI18N
        jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DELETE, 0));
        jMenuItem2.setText(resourceMap.getString("jMenuItem2.text")); // NOI18N
        jMenuItem2.setName("jMenuItem2"); // NOI18N
        jMenu1.add(jMenuItem2);

        menuBar.add(jMenu1);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        setComponent(mainPanel);
        setMenuBar(menuBar);
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList jListBooks;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTree jTreeCollections;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    // End of variables declaration//GEN-END:variables

    private void extraInit() throws Exception {
        jTreeCollections.setTransferHandler(new TreeTransferHandler());
        jListBooks.setTransferHandler(new ListTransferHandler());


        jListBooks.setModel(new javax.swing.AbstractListModel() {

            Book[] books = KindleInteractor.getBooks().toArray(
                    new Book[KindleInteractor.getBooks().size()]);

            public int getSize() {
                try {
                    return KindleInteractor.getBooks().size();
                } catch (Exception ex) {
                    Logger.getLogger(KindleCollView.class.getName()).log(Level.SEVERE, null, ex);
                }
                return 0;
            }

            public Object getElementAt(int i) {
                try {
                    return KindleInteractor.getBooks().toArray(
                        new Book[KindleInteractor.getBooks().size()])[i];
                } catch (Exception ex) {
                    Logger.getLogger(KindleCollView.class.getName()).log(Level.SEVERE, null, ex);
                }
                return null;
            }
        });
        
        jTreeCollections.addMouseListener(new PopupMenuListener());     
        jTreeCollections.addFocusListener(new ListTreeSelection());
        
        jListBooks.addMouseListener(new PopupMenuListener());
        jListBooks.addFocusListener(new ListTreeSelection());
        
        BookHashIniter bhi = new BookHashIniter(jTreeCollections);
        Thread initTitles = new Thread(bhi);
        initTitles.start();
                
        
    }

    private void TreeModelInit() {
        jTreeCollections.setModel(new UIHelper().getTreeModel());
    }

    @Action
    public Task DoGenerationTask() {
        return new DoGenerationTaskTask(getApplication());
    }

    private class DoGenerationTaskTask extends org.jdesktop.application.Task<Object, Void> {
        DoGenerationTaskTask(org.jdesktop.application.Application app) {
            // Runs on the EDT.  Copy GUI state that
            // doInBackground() depends on from parameters
            // to DoGenerationTaskTask fields, here.
            super(app);
        }
        @Override protected Object doInBackground() {
            try {
                // Your Task's code here.  This method runs
                // on a background thread, so don't reference
                // the Swing GUI from here.
                KindleInteractor.saveCollections();
            } catch (Exception ex) {
                Logger.getLogger(KindleCollView.class.getName()).log(Level.SEVERE, null, ex);
            }
            return null;  // return your result
        }
        @Override protected void succeeded(Object result) {
            // Runs on the EDT.  Update the GUI based on
            // the result computed by doInBackground().
        }
    }

    @Action
    public void DelElement() {
        UIHelper uiHelp = new UIHelper();
        uiHelp.delCollectionElement(jTreeCollections);
        uiHelp.delBookElement(jListBooks);
    }


    DragSource ds;
    private JDialog aboutBox;
    
    class BooksListCellRenderer extends DefaultListCellRenderer {
        /* This is the only method defined by ListCellRenderer.  We just
         * reconfigure the Jlabel each time we're called.
         */
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean iss,    
        		boolean chf)    
        {
            super.getListCellRendererComponent(list, value, index, iss, chf);


    	if (!((Book)value).getCollections().isEmpty() ) {
    		this.setForeground(new Color(150,150,150)); 
    		}

    	return this;
        }
    }
}


